<?php
namespace app\index\controller;
use think\Controller;
use think\Db;
use think\Request;
use think\Loader;


class Front extends Controller
{
    /*
    author:hardingCheng
    */
    //实时更新车辆的位置
    public function getTruckPosition()
    {
        $parameter = Request::instance()->post();
        $parameter['positiontime']=date('y-m-d H:i:s',time());
        $result=Db::table('all_user')->where('phone',$parameter['phone'])->field('truckid')->find();
        // $data = Db::query("INSERT INTO truck_position(truckid,longitute,latitude,positiontime) VALUES ($parameter['truckid'],$parameter['longitute'],$parameter['latitude'],$parameter['positiontime']");
        $data =Db::table('truck_position')->where('truckid',$result['truckid'])->update(['longitude'=>$parameter['longitude'],'latitude'=>$parameter['latitude'],'positiontime'=>$parameter['positiontime']]);
        $ut = new Utiltool($data);
        return $ut->getpdata();
    }
    //获取车辆的列表信息
    public function getTruckOrder()
    {
    //    $parameter = Request::instance()->post();
    //    $parameter=Request::instance()->param('phone');
    //    $result=Db::table('all_user')->where('phone',$parameter)->field('truckid')->find();
    //    $data=Db::table('all_data')->where('truckid','=',$result['truckid'])->where('state','=',4)->field('freightId,kilometre,bourn,truckload,isEmergency,id')->select();
    //    if(count($data)==0)
    //     {
    //         $data['information']=0;
    //     }else{
    //         array_walk_recursive($data, function (& $val, $key ) {
    //             if ($val === null) {
    //                 $val = '暂无数据';
    //             }     
    //         });
    //     }
    //    $ut = new Utiltool($data);
    //    return $ut->getpdata();
       $parameter=Request::instance()->param('phone');
       $result=Db::table('all_user')->where('phone',$parameter)->field('truckid,state,singlestate')->find();
       if($result['singlestate']==1){
            $data=Db::table('all_data')->where('state','=',4)->field('freightId,kilometre,bourn,truckload,isEmergency,id')->select();
            $result1= array();
            $result3= array();
            $max=0;
            $result2=['id'=>0,'truckload'=>0,'datalist'=>0];
            foreach ($data as $key => $info) {
                $result1[$info['freightId']][] = $info;
            }
            foreach ($result1 as $key => $info) {
                $result2['id']=$key;
                if($result1[$key][0]['isEmergency']==null)
                {
                    $result1[$key][0]['isEmergency']=0;
                }else{
                    $result2['isEmergency']= $result1[$key][0]['isEmergency'];
                }
                $result2['datalist']= $info;
                for($i=0;$i<count($result1[$key]);$i++)
                {
                    $result2['truckload']+=(float)$result1[$key][$i]['truckload'];
                    $result2['kilometre']=$max;
                    if($max<=(float)$result1[$key][$i]['kilometre'])
                    {
                        $max=(float)$result1[$key][$i]['kilometre'];
                    }
                }
                array_push($result3,$result2);
                $result2['truckload']=0;
                $max=0;
            }
            if(count($result3)==0)
            {
                $result3['information']=0;
            }else{
                array_walk_recursive($result3, function (& $val, $key ) {
                    if ($val === null) {
                        $val = '暂无数据';
                    }     
                });
            }
            }else {
            $result3=null;
         }
       $ut = new Utiltool($result3);
       return $ut->getpdata();
    }
    //获取列表的详细信息
    public function getTruckOrderDetailed()
    {
        $freightId=Request::instance()->param('freightId');
        $phone=Request::instance()->param('phone');
        $data=Db::table('all_data')
        ->where('freightId','=',$freightId)
        ->where('state','=',4)
        ->field('freightId,orderid,bourn,board,volume,kilometre')
        //->field('freightId,orderid,customer,bourn,board,flute,format,area,oneofarea,volume,truckload,coefficient,kilometre')
        ->select();
        foreach($data as $key=>$val)
        {
            $result=Db::table('distribution_point')
            ->where('bournname',$val['bourn'])
            ->field('longitude,latitude')   
            ->find();
            $result1=Db::table('factory_location')
            ->where('factoryname','亿丰伟业（燕郊）')
            ->field('factoryname,longitude,latitude')
            ->find();
            $data[$key]['bournlongitude']=$result['longitude'];
            $data[$key]['bournlatitude']=$result['latitude'];
            $data[$key]['factoryname']=$result1['factoryname'];
            $data[$key]['factorylongitude']=$result1['longitude'];
            $data[$key]['factorylatitude']=$result1['latitude'];
        }
        if(count($data)==0)
        {
            $data['information']=1;
        }else{
            array_walk_recursive($data, function (& $val, $key ) {
                if ($val === null) {
                    $val = '暂无数据';
                }     
            });
        }
        $ut = new Utiltool($data);
        return $ut->getpdata();
    }
    //获取订单的厂家和送货地点的百度经纬度
    public function getTruckOrderDetailedTwo()
    {
        $freightId=Request::instance()->param('freightId');
        $data=Db::table('all_data')
        ->where('freightId','=',$freightId)
        ->where('state','=',1)
        ->field('bourn,orderid')
        //->field('freightId,orderid,customer,bourn,board,flute,format,area,oneofarea,volume,truckload,coefficient,kilometre')
        ->select();
        foreach($data as $key=>$val)
        {
            $result=Db::table('distribution_point')
            ->where('bournname',$val['bourn'])
            ->field('longitude,latitude')   
            ->find();
            $result1=Db::table('factory_location')
            ->where('factoryname','亿丰伟业（燕郊）')
            ->field('factoryname,longitude,latitude')
            ->find();
            $data[$key]['orderid']=$val['orderid'];
            $data[$key]['bournlongitude']=$result['longitude'];
            $data[$key]['bournlatitude']=$result['latitude'];
            $data[$key]['factorylongitude']=$result1['longitude'];
            $data[$key]['factorylatitude']=$result1['latitude'];
        }
        if(count($data)==0)
        {
            $data==null;
        }else{
            array_walk_recursive($data, function (& $val, $key ) {
                if ($val === null) {
                    $val = '暂无数据';
                }     
            });
        }
        $ut = new Utiltool($data);
        return $ut->getpdata();
    }
    //接单
    public function getTruckAcceptOrders() 
    { 
        // //phone
        // $parameter = Request::instance()->post();
        // $parameter['acceptdate']=date('y-m-d H:i:s',time());
        // $data =Db::table('all_data')
        // ->where('id',$parameter['id'])
        // ->where('freightId',$parameter['freightId'])
        // ->update(['state'=> 1,'acceptdate' => $parameter['acceptdate']]);
        // // $data = Db::execute("UPDATE all_data SET state = 1,
        // // acceptdate='".$parameter['acceptdate'].
        // // "' WHERE id ='".$parameter['id']."' AND 
        // // freightId ='".$parameter['freightId']."'");
        // $ut = new Utiltool($data);  
        // return $ut->getpdata();
        $parameter = Request::instance()->post();
        $result=Db::table('all_user')->where('phone',$parameter['phone'])->field('truckid,state')->find();
        $result2=['information'=>null];
        if($result['state']==0)
        {
            $result5 =Db::table('all_data')
            ->where('freightId',$parameter['id'])
            ->field('state')   
            ->find();
            if($result5['state']==1)
            {
                $result2['information']=1;
            }else{
                $parameter['acceptdate']=date('y-m-d H:i:s',time());
                // $data =Db::table('all_data')
                // ->where('freightId',$parameter['id'])
                // ->where('state',4)
                // ->update(['state'=> 1,'acceptdate' => $parameter['acceptdate'],'truckid'=>$result['truckid']]);
                // if($data!=0)
                // {
                //     $data1 =Db::table('all_user')
                //     ->where('phone',$parameter['phone'])
                //     ->update(['state'=> 1]);
                //     $result2=$data;
                // }
                $result2=Db::execute("UPDATE all_data,all_user 
                SET all_data.state =1,all_data.acceptdate = '".$parameter['acceptdate']."',all_user.lastdate = '".$parameter['acceptdate']."' ,all_data.truckid='".$result['truckid']."' ,all_user.state =1  
                WHERE all_user.phone = '".$parameter['phone']."' AND all_data.freightId= '".$parameter['id']."' AND all_data.state = 4");
                
            }
        }else{
            $result2=null;
        }
        $ut = new Utiltool($result2);  
        return $ut->getpdata();

    }
    //退单
    public function getTruckCancelOrders() 
    { 
        // //phone
        $parameter = Request::instance()->post();
        $result=Db::table('all_user')->where('phone',$parameter['phone'])->field('truckid,state')->find();
        $parameter['canceldate']=date('y-m-d H:i:s',time());
        // $data1 =Db::table('all_user')
        // ->where('phone',$parameter['phone'])
        // ->update(['state'=> 0]);
        // $data =Db::table('all_data')
        // ->where('truckid',$result['truckid'])
        // ->where('freightId',$parameter['freightId'])
        // ->where('state',1)
        // ->update(['state'=> -1,'canceldate'=>$parameter['canceldate'],'mark'=>$parameter['mark']]);
        $data=Db::execute("UPDATE all_user,all_data
        SET all_user.state = 0,all_data.state=-1,all_data.canceldate='".$parameter['canceldate']."',all_data.mark='".$parameter['mark']."'
        WHERE all_user.phone='".$parameter['phone']."' AND all_data.truckid ='".$result['truckid']."' AND all_data.freightId='".$parameter['freightId']."' AND all_data.state = 1");
        $ut = new Utiltool($data);
        return $ut->getpdata();
    }
    //结束订单
    public function getTruckEndOrders() 
    { 
        //phone
        $parameter = Request::instance()->post();
        $resulttruck=Db::table('all_user')->where('phone',$parameter['phone'])->field('truckid')->find();
        $parameter['enddate']=date('y-m-d H:i:s',time());
        // $data =Db::table('all_data')
        // ->where('truckid',$resulttruck['truckid'])
        // ->where('freightId',$parameter['freightId'])
        // ->where('state',1)
        // ->update(['state'=> 2,'enddate' => $parameter['enddate']]);
        // $result =Db::table('all_user')
        // ->where('phone',$parameter['phone'])
        // ->update(['state'=> 0]);
        $data=Db::execute(" UPDATE all_data,all_user 
        SET all_data.state = 2,all_data.enddate='".$parameter['enddate']."',all_user.state=0
        WHERE all_data.truckid='".$resulttruck['truckid']."' AND all_data.freightId='".$parameter['freightId']."' AND all_data.state =1 AND all_user.phone='".$parameter['phone']."'");
        $resultvolume=Db::table('all_data')
        ->where('truckid',$resulttruck['truckid'])
        ->where('freightId',$parameter['freightId'])
        ->where('state',2)
        ->sum('volume');
        $truckvolume=Db::table('vehicle_load')
        ->where('licensePlate',$resulttruck['truckid'])
        ->field('volume')
        ->find();
        if((float)$resultvolume>(float)$truckvolume['volume'])
        {
            $datavolume =Db::table('vehicle_load')
            ->where('licensePlate',$resulttruck['truckid'])
            ->update(['volume'=> $resultvolume]);
        }
        $ut = new Utiltool($data);
        return $ut->getpdata();
    }
    //手机端向服务端插入障碍点
    public function getTruckObstacle()
    { 
        $parameter = Request::instance()->post();
        $parameter['positiontime']=date('y-m-d H:i:s',time());
        $parameter['state']=1;
        $result=Db::table('map_obstacle')->insert($parameter);
        $ut = new Utiltool($result);
        return $ut->getpdata();
    }
    //服务端向手机端返回障碍点
    public function putTruckObstacle()
    {
        $timenew=date('y-m-d H:i:s',time());
        $timebefore=date('y-m-d H:i:s',strtotime("-5 hours"));
        $result = Db::query("
        SELECT all_user.name,map_obstacle.longitude,map_obstacle.latitude,map_obstacle.positiontime  
        FROM all_user,map_obstacle 
        WHERE all_user.phone=map_obstacle.phone AND map_obstacle.positiontime  between '$timebefore' AND '$timenew' and map_obstacle.state = 1");
        $ut = new Utiltool($result);    
        return $ut->getpdata();
    }
    //手机端的修改密码
    public function  getUserModifyInformation()
    {
        $parameter=Request::instance()->post();
        $data =Db::table('all_user')
        ->where('phone',$parameter['id'])
        ->where('password',md5($parameter['oldpassword']))
        ->update(['password'=>md5($parameter['newpassword'])]);
        $ut = new Utiltool($data);    
        return $ut->getpdata();
    }
    //车辆的（出车）状态
    public function getsetTruckSingleState()
    {
        //$reauestdata=['information'=>null,'datalist'=>null];
        $parameter=Request::instance()->post();
        if($parameter['ckgrp']=='get_state'){
            $data =Db::table('all_user')
            ->where('phone',$parameter['phone'])
            ->field('singlestate')
            ->find();
        }else if($parameter['ckgrp']=='set_state'){
            $data =Db::table('all_user')
            ->where('phone',$parameter['phone'])
            ->update(['singlestate'=>1]);
        }
        $ut = new Utiltool($data);    
        return $ut->getpdata(); 
    }
    
    public function getsetObstaclePoint(){
        $parameter=Request::instance()->post();
        if($parameter['pointgrp']=='get_state'){
            $data =Db::table('map_obstacle')
            ->where('phone',$parameter['phone'])
            ->where('state',1)
            ->field('phone,longitude,latitude,detourdistance,positiontime,id')
            ->select();
        }else if($parameter['pointgrp']=='set_state'){
            $data =Db::table('map_obstacle')
            ->where('phone',$parameter['phone'])
            ->where('id',$parameter['id'])
            ->update(['state'=>0]);
        }
        $ut = new Utiltool($data);    
        return $ut->getpdata(); 
    }
    //获取历史订单列表
    public function getHistoricalOrder(){
        $parameter=Request::instance()->param();
        $data1=Db::table('all_user')->where('phone',$parameter['phone'])->field('truckid')->find();
        $likeyear=date("Y").'%';
        $data=Db::table('all_data')
        ->where('truckid','=',$data1['truckid'])
        ->where('state','=',2)
        ->where('createdate','like',$likeyear)
        ->order('createdate desc')
        ->field('freightId,orderid,customer,bourn,board,flute,format,area,oneofarea,volume,truckload,coefficient,kilometre,enddate')
        ->select();
        $result1= array();
        $result3= array();
        $max=0;
        $result2=['id'=>0,'truckload'=>0,'datalist'=>0];
        foreach ($data as $key => $info) {
            $result1[$info['freightId']][] = $info;
        }
        foreach ($result1 as $key => $info) {
            $result2['id']=$key;
            $result2['datalist']= $info;
            for($i=0;$i<count($result1[$key]);$i++)
            {
                $result2['truckload']+=(float)$result1[$key][$i]['truckload'];
                $result2['kilometre']=$max;
                if($max<=(float)$result1[$key][$i]['kilometre'])
                {
                    $max=(float)$result1[$key][$i]['kilometre'];
                }
            }
            array_push($result3,$result2);
            array_slice($result3,0,9);
            $result2['truckload']=0;
            $max=0;
        }
        if(count($result3)!=0){
            array_walk_recursive($result3, function (& $val, $key ) {
                if ($val === null) {
                    $val = '暂无数据';
                }     
            });
        }else{
            $result3=null;
        }
        $ut = new Utiltool($result3);    
        return $ut->getpdata(); 
    }
    //获取已接订单的信息
    public function getAlreadyOrderInfo(){
        $parameter=Request::instance()->post();
        $data1=Db::table('all_user')->where('phone',$parameter['phone'])->field('truckid')->find();
        $data=Db::table('all_data')
        ->where('truckid','=',$data1['truckid'])
        ->where('state','=',1)
        ->field('freightId,orderid,customer,bourn,board,flute,format,area,oneofarea,volume,truckload,coefficient,kilometre')
        ->select();
        $result1= array();
        $result3= array();
        $max=0;
        $result2=['id'=>'0','truckload'=>'0','datalist'=>'0'];
        foreach ($data as $key => $info) {
            $result1[$info['freightId']][] = $info;
        }
        foreach ($result1 as $key => $info) {
            $result2['id']=$key;
            $result2['datalist']= $info;
            for($i=0;$i<count($result1[$key]);$i++)
            {
                $result2['truckload']+=(float)$result1[$key][$i]['truckload'];
                $result2['kilometre']=$max;
                if($max<=(float)$result1[$key][$i]['kilometre'])
                {
                    $max=(float)$result1[$key][$i]['kilometre'];
                }
            }
            $result2['truckload']=0;
            $max=0;
        }
        if(count($result2)!=0){

            if(strcmp($result2['id'],'0')==0)
            {
                unset($result2['id']);
                unset($result2['truckload']);
                unset($result2['datalist']);
                unset($result2['kilometre']);
            }else{
                array_walk_recursive($result2, function (& $val, $key ) {
                    if ($val === null) {
                        $val = '暂无数据';
                    }     
                });
            }
        }else{
            $result2=null;
        }
        $ut = new Utiltool($result2);    
        return $ut->getpdata(); 
    }
    //获取用户的基本信息
    public function getUserDeliveryTotal(){
        $parameter=Request::instance()->post();
        $year=date('Y');
        $month=date('m');
        $yeardata = Db::query(" SELECT COUNT(all_data.truckid) as yeartotal
            FROM all_user,all_data 
            WHERE createdate   LIKE '".$year.'%'."' and all_data.state = 2  and  all_user.phone  = '".$parameter['phone']."' and all_user.truckid = all_data.truckid
            ");
        $monthdata = Db::query(" SELECT COUNT(all_data.truckid) as monthtotal
            FROM all_user,all_data 
            WHERE createdate   LIKE '".$year.'-'.$month.'%'."' and all_data.state = 2  and  all_user.phone  = '".$parameter['phone']."' and all_user.truckid = all_data.truckid
            ");
        $data['yeartotal']=$yeardata[0]['yeartotal'];
        $data['monthtotal']=$monthdata[0]['monthtotal'];
        $ut = new Utiltool($data);    
        return $ut->getpdata(); 
    }
    public function login(){
        $userInfo = Request::instance()->post();
        $validate = Loader::validate('Modeluser');
        if(!$validate->check($userInfo)){
            $ut = new Utiltool(null);
            return $ut->getpdata();
        }
        $result = Db::table("all_user")
        ->where("phone",$userInfo["phone"])
        ->where("password",md5($userInfo["password"]))
        ->field('username,truckid')
        ->find();
        if(!$result){
            $ut = new Utiltool(null);
            return $ut->getpdata();
        }
        $ut = new Utiltool($result);
        return $ut->getpdata();
    }
    //手机端获取公里数
    public function getPhoneKilometre(){
        $parameter=Request::instance()->post();
        $updatekilometre=Db::execute("UPDATE all_data
        SET kilometre='".$parameter['kilometre']."'
        WHERE orderid='".$parameter['orderid']."' AND freightId ='".$parameter['freightId']."'");
        $ut = new Utiltool($updatekilometre);
        return $ut->getpdata();    
    }
    public function getUserInfoByPhone(){
        $phone = Request::instance()->post("phone");
        if(!$phone){
            $ut = new Utiltool(null);
            return $ut->getpdata();
        }
        $userInfo = Db::table("all_user")
        ->where("phone",$phone)
        ->field("truckid,name,sex")
        ->find();   
        $ut = new Utiltool($userInfo);
        return $ut->getpdata();
    }
}